<?php

namespace app\admin\controller\xykeep\course;

use addons\epay\library\Service;
use app\admin\model\Admin;
use app\api\model\xykeep\User;
use app\api\model\xykeep\course\Order as apiCourseOrder;
use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 课程订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\xykeep\course\Order
     */
    protected $model = null;
    protected $relationSearch = true;
    protected $searchFields = 'order_sn,user.nickname,name.nickname';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\xykeep\course\Order;
        $this->view->assign("payTypeList", $this->model->getPayTypeList());
        $this->view->assign("platformList", $this->model->getPlatformList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->assignconfig('statusList',$this->model->getStatusList());

        $this->assignconfig('typeList',$this->model->getTypeList());
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $timesec_id = input('timesec_id/d',0);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();

        $where2 = [];
        if($timesec_id){
            $where2['course_timesec_id'] = $timesec_id;
            $order = 'service_start_time desc';
        }else{
            $order = 'createtime desc';
        }
        $list = $this->model
            ->with(['user'])
            ->where($where2)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $items = $list->items();
        foreach ($items as &$item) {
            $ext = json_decode($item['ext'],true);

        }
        $result = ['total' => $list->total(), 'rows' => $items];

        return json($result);
    }

    /**
     * 详情
     *
     * @param $ids
     */
    public function detail($id = null)
    {
        $row = $this->model->with(['user'])->where(['id'=>$id])->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }


        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     * 驳回退款申请
     */
    public function refund_back($id = null)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if($row['status'] < 1){
            $this->error(__('订单状态错误', ''));
        }


        $result = false;
        Db::startTrans();
        try {

            $result = $row->allowField(true)->save([
                'refund_before' => 0,
                'is_free' => 0,
                'status'=>$row['refund_before'],
                'refund_time'=>null
            ]);

            if($result){
                $result = true;
            }else{
                $result = false;
                Db::rollback();
            }

            Db::commit();
        }catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success('驳回退款成功');
    }

    /**
     * 退款
     */
    public function refund($id = null)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if($row['status'] < 1){
            $this->error(__('订单状态错误', ''));
        }


        $result = false;
        Db::startTrans();
        try {

            $result = $row->allowField(true)->save(['status'=>-3,'refundtime'=>time()]);

            $params['order'] = $row;
            $params['type'] = 'course';
            \think\Hook::listen('xykeep_order_refund_after', $params);

            if($result){
                $result = true;
            }else{
                $result = false;
                Db::rollback();
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success('退款成功');
    }

    /**
     * 核销
     */
    public function order_verify(){
        $params = $this->request->post();
        $res = apiCourseOrder::verifyOrder($params['order_sn']);

        if($res){
            $this->success('核销成功');
        }else{
            $this->error('核销失败');
        }
    }


}
